//
//  ECUIVC_Login.m
//  Edu_iOS
//
//  Created by yanyan on 2017/9/8.
//  Copyright © 2017年 yanyan. All rights reserved.
//

#import "ECUIVC_Login.h"
#import "ECUITextField_Account.h"
#import "ECPrompt_Validate.h"
#import "MBProgressHUD+JDragon.h"
#import "UINavigationBar+Awesome.h"
#import "ECRegisteredViewController.h"
#import "ECForgetPasswordViewController.h"
#import "CYAnimation.h"
#import "ECOthersLoginViewController.h"
#import <TTTAttributedLabel.h>
#import "ECRegistBindingController.h"
#import "CYDataHelper.h"
#import "ECRegularExpression.h"
#import "ECUIVC_Home.h"

#import <ShareSDK/ShareSDK.h>
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>

// 导入头文件
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>

#import <AFHTTPSessionManager.h>

#define Textfield_height        (960*0.1406)      //封装输入框的高度
#define Font_registerLab        15              //注册lab字体大小


@interface ECUIVC_Login ()<TTTAttributedLabelDelegate>
{
    UIImageView *logoView;
    ECUITextField_Account *uitf_name;
    ECUITextField_Account *uitf_password;
    ECUButton *loginBtn;
    TTTAttributedLabel *label;
    NSRange lineRange;
}
@end

@implementation ECUIVC_Login

- (void)viewDidLoad {
    [super viewDidLoad];
    
}
- (void)addSubviews
{
    [super addSubviews];
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.title = @"";
    [self.navigationController.navigationBar lt_setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"registered_return"] style:UIBarButtonItemStylePlain target:self action:@selector(action_dismiss)];

    logoView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"LoginIcon"]];
    [self.view addSubview:logoView];
    
    [logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).mas_offset(kNavHeight);
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(@(kProportion_Width(420)));
        make.height.mas_equalTo(@(kProportion_Width(420) * 0.3514));
    }];
    [self.view layoutIfNeeded];
    
    uitf_name = [[ECUITextField_Account alloc]initWithFrame:CGRectMake(kProportion_Width(60), CGRectGetMaxY(logoView.frame)+ kProportion_Width(60), kScreenWidth - kProportion_Width(MarginLeft_Textfield*2) , kProportion_Height(Textfield_height)) placeholder:@"手机号/用户名/邮箱" leftImage:[UIImage imageNamed:@"tel_user"]];
    [self.view addSubview:uitf_name];
    //password textfield
    uitf_password = [[ECUITextField_Account alloc]initWithFrame:CGRectMake(kProportion_Width(60), CGRectGetMaxY( uitf_name.frame) + kProportion_Width(MarginHeight_textfield), kScreenWidth - kProportion_Width(MarginLeft_Textfield*2) , kProportion_Height(Textfield_height)) placeholder:@"密码" leftImage:[UIImage imageNamed:@"pwd_user"]];
    uitf_password.textField.frame = CGRectMake(uitf_password.textField.frame.origin.x, uitf_password.textField.frame.origin.y, kScreenWidth - kProportion_Width(MarginLeft_Textfield*2) - 100, uitf_password.textField.frame.size.height);
    [uitf_password.rightButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    
    uitf_password.rightButton.titleLabel.font = [UIFont systemFontOfSize:Font_registerLab*kPercentage];
    [uitf_password.rightButton setTitleColor: [UIColor colorWithHexString:@"#808080"] forState:UIControlStateNormal];

    WeakSelf(weakSelf);
    uitf_password.block_rightButton = ^(id obj){
        [weakSelf block_forgetPassword];
    };

    uitf_password.isSecureTextEntry = YES;
    [self.view addSubview:uitf_password];
    [uitf_password.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.mas_equalTo(uitf_password.textField.mas_right).mas_offset(0);
        make.centerY.equalTo(uitf_password.textField);
        make.size.mas_equalTo(CGSizeMake(100, 30));
    }];
    
    
    // login btn
    loginBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"flatButton_colorNormal"] forState:UIControlStateNormal];
    loginBtn.frame = CGRectMake(kProportion_Width(60), CGRectGetMaxY(uitf_password.frame) + kProportion_Width(MarginHeight_textfield), kScreenWidth - kProportion_Width(60*2),(kScreenWidth - kProportion_Width(60*2))* 0.1406);
    [loginBtn addTarget:self action:@selector(action_Login) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"flatButton_colorSelected"] forState:UIControlStateHighlighted];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:ceil(20)];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [self.view addSubview:loginBtn];
    
    NSString           *text  = @"还不是会员? 注册新用户";
    label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(loginBtn.frame) + kProportion_Width(90), kScreenWidth, kProportion_Width(50))];
    label.textColor = [UIColor colorWithHexString:@"#808080"];
    NSMutableAttributedString *atributeStr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#808080"],NSFontAttributeName :[UIFont systemFontOfSize:Font_registerLab]}];
    //可以传属性字符串
    label.text            = atributeStr;
    label.font            = [UIFont systemFontOfSize:Font_registerLab];
    label.numberOfLines   = 0;
    label.textAlignment = NSTextAlignmentCenter;
    //链接的属性字符串
    label.linkAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#ff6600"], NSFontAttributeName:[UIFont systemFontOfSize:Font_registerLab]};
    
    NSRange serviceRange2 = [text rangeOfString:@"注册新用户"];
    label.delegate = self;
    [self.view addSubview:label];
    [label addLinkToURL:[NSURL URLWithString:@""] withRange:serviceRange2];
    
    [self addThirdPartWidget];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar lt_setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //[self.navigationController.navigationBar lt_reset];

}
#pragma mark - 忘记密码 -
- (void)block_forgetPassword{
    [self.view endEditing:YES];
    ECForgetPasswordViewController *uivc_forgetpwd = [[ECForgetPasswordViewController alloc]init];
    uivc_forgetpwd.type_sendCode = @"sms_change_password";//用于区分绑定下的忘记密码操作
    uivc_forgetpwd.type_checkNext = @"sms_change_password";
    [self.navigationController pushViewController:uivc_forgetpwd animated:YES];

}
//   登录 点击
- (void)action_Login{
    [self.view endEditing:YES];
    DLog(@"ok");
    
    if ([CYDataHelper isNull:uitf_name.textField.text] == NO){
        if ([CYDataHelper isNull:uitf_password.textField.text] == NO) {

            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [HWHttpTool requestWithMethod:@"POST"
                                      url:URL_POST_Login
                                   params:@{@"nickname":uitf_name.textField.text,
                                            @"password":uitf_password.textField.text}
                                  headers:nil
                                  success:^(id json) {
                                      [self configLoginWithJsonData:json];
                                      
                                  } failure:^(NSError *error) {
                                      [MBProgressHUD hideHUDForView:self.view animated:YES];
                                      [MBProgressHUD showTipMessageInWindow:@"账号或密码错误"];
                                  }];
        }else{
            [MBProgressHUD showTipMessageInWindow:@"请输入密码"];
        }
    }else{
        [MBProgressHUD showTipMessageInWindow:@"请输入账号"];
    }
}

- (void)addThirdPartWidget{
    UIView *othersView = [[UIView alloc]init];
    [self.view addSubview:othersView];
    UIView *firstLine = [[UIView alloc]init];
    firstLine.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
    [othersView addSubview:firstLine];
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.font = [UIFont systemFontOfSize:ceil(12 * kPercentage)];
    titleLabel.textColor = [UIColor colorWithHexString:@"#808080"];
    titleLabel.text = @"第三方登录";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [othersView addSubview:titleLabel];
    UIView *secondLine = [[UIView alloc]init];
    secondLine.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
    [othersView addSubview:secondLine];
    
    //contentView
    UIView *contentView = [[UIView alloc]init];
    [self.view addSubview:contentView];
    ECUButton *qqBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
    [qqBtn setBackgroundImage:[UIImage imageNamed:@"qqLogin"] forState:UIControlStateNormal];
    [qqBtn addTarget:self action:@selector(action_qq_OR_wx:) forControlEvents:UIControlEventTouchUpInside];
    qqBtn.tag = 11;
    [contentView addSubview:qqBtn];
    ECUButton *wxBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
    [wxBtn setBackgroundImage:[UIImage imageNamed:@"wxLogin"] forState:UIControlStateNormal];
    [wxBtn addTarget:self action:@selector(action_qq_OR_wx:) forControlEvents:UIControlEventTouchUpInside];
    wxBtn.tag = 12;
    [contentView addSubview:wxBtn];
    
    WeakSelf(weakSelf);
    [firstLine mas_makeConstraints:^(MASConstraintMaker *make) {
        CGFloat firstLine_width = (kScreenWidth - 80 - kProportion_Width(60)*2 - 5 * 2)/2;
        make.width.equalTo(@(firstLine_width));
        make.height.equalTo(@(1));
        make.centerY.equalTo(titleLabel.mas_centerY);
        make.left.equalTo(@(kProportion_Width(60)));
    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(othersView.mas_centerY);
        make.centerX.equalTo(othersView.mas_centerX);
        make.width.equalTo(@(80));
        make.height.equalTo(othersView.mas_height);
    }];
    
    [secondLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right).offset(5);
        make.width.equalTo(firstLine);
        make.height.equalTo(firstLine);
        make.centerY.equalTo(firstLine);
    }];

    [othersView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(contentView.mas_top).offset(-(kProportion_Width(60)));
        make.width.equalTo(@(kScreenWidth));
        make.height.equalTo(@(15));
    }];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(weakSelf.view.mas_centerX);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).mas_offset(-(kProportion_Width(150)));
        make.height.mas_equalTo(contentView.mas_width).multipliedBy(126.f/960.f);
        make.left.mas_equalTo(firstLine.mas_left);
        make.right.mas_equalTo(secondLine.mas_right);
    }];
    
    [qqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(contentView.mas_centerY);
        make.left.equalTo(contentView.mas_left);
        make.height.mas_equalTo(contentView.mas_height);
        make.right.equalTo(wxBtn.mas_left).offset(-kProportion_Width(60));
    }];
    [wxBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(qqBtn.mas_right).offset(kProportion_Width(60));
        make.centerY.mas_equalTo(qqBtn.mas_centerY);
        make.width.height.equalTo(qqBtn);
        make.right.equalTo(contentView.mas_right);
    }];
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    if ([QQApiInterface isQQInstalled]) {
        [arr addObject:@"QQ"];
    }

    if ([WXApi isWXAppInstalled]) {
        [arr addObject:@"微信"];
    }

    if (arr.count == 0) {
        qqBtn.hidden = YES;
        wxBtn.hidden = YES;
        othersView.hidden = YES;

    }else if (arr.count == 1){
        NSString *iconStr;
        if ([arr containsObject:@"QQ"]) {//只有安装QQ
            iconStr = @"qqLogin";
        }else{//只有安装微信
            iconStr = @"wxLogin";
        }

        qqBtn.hidden = YES;
        wxBtn.hidden = YES;

        ECUButton *styleBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
        [styleBtn setBackgroundImage:[UIImage imageNamed:iconStr] forState:UIControlStateNormal];
        [styleBtn addTarget:self action:@selector(action_qq_OR_wx:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:styleBtn];
        styleBtn.tag = 13;
        styleBtn.titleLabel.font = [UIFont systemFontOfSize:0];
        [styleBtn setTitle:iconStr forState:0];


        [styleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(contentView.mas_centerY);
            make.centerX.equalTo(contentView.mas_centerX);
            make.width.equalTo(qqBtn.mas_width);
            make.height.equalTo(qqBtn.mas_height);
        }];

    }
}

-(void)action_dismiss{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)action_qq_OR_wx:(ECUButton *)btn{
    SSDKPlatformType platformType;
    NSInteger tag_btn = btn.tag;
    if (tag_btn == 11) {
        platformType = SSDKPlatformTypeQQ;
    }else if (tag_btn == 12){
        platformType = SSDKPlatformTypeWechat;
    }else{
        NSString *title_btn = btn.titleLabel.text;
        if ([title_btn isEqualToString:@"qqLogin"]) {
            platformType = SSDKPlatformTypeQQ;
        }else{
            platformType = SSDKPlatformTypeWechat;
        }
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //0B5F631C738DA85CDEE04BD3D75FA25B
    //shareSDK 获取三方授权用户信息
    [ShareSDK getUserInfo:platformType
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error){
               
               if (platformType == SSDKPlatformTypeQQ) {
                   SSDKCredential *dict = user.credential;
                   NSString *ulr = [NSString stringWithFormat:@"https://graph.qq.com/oauth2.0/me?access_token=%@&unionid=1",dict.token];
                   
                   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
                   manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                   [manager GET:ulr
                     parameters:nil
                       progress:^(NSProgress * _Nonnull downloadProgress) {}
                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            NSLog(@"这里打印请求成功要做的事");
                            NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                            
                            NSLog(@"str = %@",string);
                            if ([string containsString:@"100016"]) {
                                [MBProgressHUD showTipMessageInWindow:@"用户凭证已过期,请重新获取"];
                                return;
                            }
                            NSRange startRange = [string rangeOfString:@"UID_"];
                            NSRange endRange = [string rangeOfString:@"""} );"];
                            NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length-1);
                            NSString *result = [string substringWithRange:range];
                            DLog(@"%@",result);
                            
                            [self otherWithPlatformType:SSDKPlatformTypeQQ andStatus:state andUnionID:result andAvatar:user.icon];
                            
                        }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
                            NSLog(@"%@",error);  //这里打印错误信息
                        }];
               }else{
                   [self otherWithPlatformType:SSDKPlatformTypeWechat andStatus:state andUnionID:[(NSDictionary *)user.rawData objectForKey:@"unionid"] andAvatar:user.icon];
               }
           }];
    
    //此方法 会每次都调取第三方客户端(注释此方法,第三方客户端只有在首次授权之后才会调出,一旦授权 不会再出现第三方客户端界面)
    [ShareSDK authorize:platformType
               settings:nil
         onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
         }];
}

-(void)otherWithPlatformType:(SSDKPlatformType)platformType andStatus:(SSDKResponseState)state andUnionID:(NSString *)unionid andAvatar:(NSString *)avatar{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSString *type = (platformType == SSDKPlatformTypeQQ)? @"qq" : @"weixin";
    if (state == SSDKResponseStateSuccess) {
        [HWHttpTool requestWithMethod:@"POST"
                                  url:URL_POST_Bind_login
                               params:@{@"type":type,
                                        @"id"  :unionid
                                        }
                              headers:nil
                              success:^(id json) {
                                  DLog(@"%@",json);
                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                  if ([json[@"code"]intValue] == 200) {
                                      if ([json[@"data"][@"bind"] intValue] == 1 ) {//已经绑定,直接登录
                                          DLog(@"前去登录");
                                          [MBProgressHUD showTipMessageInWindow:@"登录成功"];
                                          [self configLoginWithJsonData:json];
                                          
                                      }else if([json[@"data"][@"bind"] intValue] == 0){
                                          ECRegistBindingController *vc= [[ECRegistBindingController alloc]init];
                                          vc.unionid = unionid;//第三方平台返回用户数据
                                          vc.platformType = (platformType == SSDKPlatformTypeWechat) ? @"weixinweb": @"qq";//第三方平台传值
                                          vc.avatar = avatar;
                                          [self.navigationController pushViewController:vc animated:YES];
                                      }else{
                                          [MBProgressHUD showTipMessageInWindow:@"获取授权信息失败,请重试"];
                                      }
                                  }
                              }
                              failure:^(NSError *error) {
                                  [MBProgressHUD hideHUDForView:self.view animated:YES];
                                  [MBProgressHUD showTipMessageInWindow:@"验证绑定信息失败,请重试"];
                              }];
    }else{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showTipMessageInWindow:@"验证失败,请重试"];
    }
}

/**
 传入登录成功的json 配置登录信息以及发送通知
 */
-(void)configLoginWithJsonData:(id)json{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    [UserInfoManager configInfo:@{@"token":json[@"data"][@"token"]}];//暂时只保存token
    [UserInfoManager configInfo:@{@"nickName":json[@"data"][@"user"][@"nickname"]}];//姓名
    
    NSString *imageUrl = json[@"data"][@"user"][@"smallAvatar"];
    [UserInfoManager configInfo:@{@"smallAvatar":imageUrl}];//头像
    
    NSString *sign = json[@"data"][@"user"][@"signature"];
    if ([CYDataHelper isNull:sign]) {//判断是否为空 (个签这个字段返回数据和其余不一样 @"<null>")
        sign = @"";
    }
    [UserInfoManager configInfo:@{@"signAture":sign}];//个签
    
    [self.view endEditing:YES];//收起键盘
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
    
    //发送登录通知
    NSNotification *notification =[NSNotification notificationWithName:kNotifactionUserLogin object:nil userInfo:nil];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

#pragma mark 注册事件
-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    MJRefreshLog(@"注册点击事件");
    ECRegisteredViewController *vc = [[ECRegisteredViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
